//
//  SHPUserAccountViewModel.swift
//  weibo
//
//  Created by songhuipan on 16/4/20.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import Foundation

class SHPUserAccountViewModel {
    /// 创建单例，避免每次从归档中取数据，提高性能
    static let sharedUserAccount = SHPUserAccountViewModel()
    /// 用户模型
    var account:SHPUserAccount?
    
    /// access_token参数字典
    var tokenDic:[String:AnyObject]? {
        if !isExpire {
            
            return ["access_token":(account?.access_token)!]
        }
        
        return nil
    }
    /// 用户是否登录标识
    var isLogIn:Bool {
        
        return !isExpire && account?.access_token != nil
    }
    /// 判断是否过期的属性
    var isExpire:Bool {
        
        if account?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending
        {
            
            return false
        }
        
        return true
    }
    // MARK:计算型属性，类似于有返回值的函数
    private var accountPath :String {
        
        let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")

    }
    // 构造函数
    private init() {
        
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? SHPUserAccount
        
        if isExpire {
            
            print("过期了")

            account = nil
        }
    }
}
extension SHPUserAccountViewModel {
    // MARK:请求access_Token的方法
    func getAccessToken (code:String,finished:(isSuccessed:Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = [
            
            "client_id":appKey,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUrl
        ]
        NetworkTools.sharedTools.loadData(httpMethod.POST, urlString: urlString, params: params) { (responseObject, error) -> () in
            
            if error != nil {
                
                print(error)
                // 失败回调结果
                finished(isSuccessed: false)
                
                return
            }
            // 测试响应数据格式
            //let dic = NSString(data: responseObject as! NSData, encoding: NSUTF8StringEncoding)
            guard let dict = responseObject as?[String:AnyObject] else{
                
                return
            }
            
            self.account = SHPUserAccount(dic: dict)
            
            self.loadUserInfon(self.account!.uid!,finished: finished)
            
        }
    }
    /// 获取用户相关信息的方法,实现只需要传入用户uid即可加载用户相关信息
    ///
    /// - parameter account: 包含令牌和用户uid信息的模型
    func loadUserInfon(uid:String,finished:(isSuccessed:Bool)->()) {
        ///用户相关信息接口
        /// -see:[ttps://api.weibo.com/2/users/show.json](ttps://api.weibo.com/2/users/show.json)
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        guard var params = tokenDic else{
            
            print("令牌access_token为空")
            
            return
            
        }
        params["uid"] = account?.uid
        NetworkTools.sharedTools.loadData(httpMethod.GET, urlString: urlString, params: params) { (responseObject, error) -> () in
            
            if error != nil {
                print(error)
                // 失败后回调
                finished(isSuccessed: false)
                return
            }
            guard let result = responseObject as? [String:AnyObject] else {
                print("数据不是字典类型")
                return
            }
            
            self.account!.screen_name = result["screen_name"] as? String
            self.account!.avatar_large = result["avatar_large"] as? String
            // MARK:修改后的归档保存，调用这个方法后系统会调用encodeWithCoder方法
            NSKeyedArchiver.archiveRootObject(self.account!, toFile: self.accountPath)
            
            // 成功后回调，如果不写，程序会进入死循环，一直等待执行结束
            finished(isSuccessed: true)
            
        }
        
    }
}





















